package org.framework.common.api.support.json;

import java.io.IOException;

import org.framework.common.ext.util.PropertiesUtil;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;

/**
 * 根据配置文件初始化JsonMapper对象
 * <p>描述: </p>
 * <p>Company: Professional</p>
 * @author chanlong(陈龙)
 * @date 2015年12月28日 上午10:45:39
 * @version 1.0.2015
 */
public class JsonMapperSupport extends ObjectMapper{

	private static final long serialVersionUID = -8753340386198804695L;
	
	public JsonMapperSupport(){
		regiestSerializerConfig();
	}
	
	private void regiestSerializerConfig(){
		PropertiesUtil properties = PropertiesUtil.loader("/config/properties/json.properties");
		
		//当为true（默认为false）允许单引号引起字符串（不推荐）
		this.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, Boolean.valueOf(properties.getProperty("ALLOW_SINGLE_QUOTES")));
		//当为true（默认为false）允许不加引号的字段名（不推荐）
		this.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, Boolean.valueOf(properties.getProperty("ALLOW_UNQUOTED_FIELD_NAMES")));
		
		//当为true（默认为true），当bean为empty时，抛出异常
		this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, Boolean.valueOf(properties.getProperty("FAIL_ON_EMPTY_BEANS")));
		//当为true（默认为true），序列化对象时，日期格式按照时间戳的方式转换
		this.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, Boolean.valueOf(properties.getProperty("WRITE_DATES_AS_TIMESTAMPS")));
		
		//当为true（默认为true）当反序列化时，如果没有对应的属性，并且没有setter和getter方法时，抛出异常。
		this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.valueOf(properties.getProperty("FAIL_ON_UNKNOWN_PROPERTIES")));
		this.configure(DeserializationFeature.FAIL_ON_UNRESOLVED_OBJECT_IDS, Boolean.valueOf(properties.getProperty("FAIL_ON_UNRESOLVED_OBJECT_IDS")));
		//当为true（默认为false）能够让json空字符串值，在反序列化成对象时，值变为null
		this.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, Boolean.valueOf(properties.getProperty("ACCEPT_EMPTY_STRING_AS_NULL_OBJECT")));
		
		//格式化输出
		this.configure(SerializationFeature.INDENT_OUTPUT, Boolean.TRUE);
		
		//在转json时null值转为空串
		this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>(){
			@Override
			public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException{
				jgen.writeString("");
			}
		});
		
		//this.getSerializerProvider().findValueSerializer(Date.class).acceptJsonFormatVisitor(visitor, type);
	}
}
